import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
import './assets/main.css'
import authService from './services/authService'

// 创建axios实例
const apiClient = axios.create({
  baseURL: '/api', // 后端API基础路径
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  config => {
    // 在发送请求之前添加token
    const token = authService.getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  response => {
    return response.data // 直接返回响应数据
  },
  async error => {
    const originalRequest = error.config
    
    // 处理401未授权错误，尝试刷新token
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true
      
      try {
        // 调用刷新token接口
        const response = await authService.refreshToken()
        
        // 保存新token
        authService.saveLoginState(response)
        
        // 更新请求头并重新发送原请求
        originalRequest.headers.Authorization = `Bearer ${response.token}`
        return apiClient(originalRequest)
      } catch (refreshError) {
        // 刷新token失败，清除本地存储并跳转到登录页
        localStorage.removeItem('token')
        localStorage.removeItem('refreshToken')
        localStorage.removeItem('user')
        
        // 记录当前路径，用于登录后重定向
        if (router.currentRoute.value.path !== '/login') {
          router.push({
            path: '/login',
            query: { redirect: router.currentRoute.value.path }
          })
        }
        
        return Promise.reject(refreshError)
      }
    }
    
    // 提取错误信息
    const errorMessage = error.response?.data?.msg || error.message || '请求失败'
    console.error('API请求错误:', errorMessage)
    
    return Promise.reject(new Error(errorMessage))
  }
)

const app = createApp(App)

// 将apiClient挂载到全局属性
app.config.globalProperties.$api = apiClient

app.use(router)

app.mount('#app')